<template>
  <a-drawer title="入学参考科目添加" :width="windowWidth" placement="right" :closable="false" @close="onClose" :visible="referenceManageAddVisiable"
    style="height: calc(100% - 55px);overflow: auto;padding-bottom: 53px;">
    <a-form :form='form'>
      <a-row :gutter="48">
        <a-col :sm="{span:12}" :lg="{span:12}">
          <a-form-item label="科目码">
            <a-input placeholder="请输入..."  v-decorator="[
                    'kmbm',
                    {
                        rules: [{ required: true, message: '请输入科目码!' }],
                    }
                    ]" />
          </a-form-item>
        </a-col>
        <a-col :sm="{span:12}" :lg="{span:12}">
          <a-form-item label="科目类型">
            <a-select :allowClear="true" showSearch optionFilterProp="children"  v-decorator="[
                    'kmlxm',
                    {
                        rules: [{ required: true, message: '请输入科目类型!' }],
                    }
                    ]">
              <a-select-option v-for="i in TYPE0390" :key="i.id" :value="i.code">{{ i.name }}</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :sm="{span:12}" :lg="{span:12}">
          <a-form-item label="科目名称">
            <a-input placeholder="请输入..."  v-decorator="[
                    'kmmc',
                    {
                        rules: [{ required: true, message: '请输入科目名称!' }],
                    }
                    ]" />
          </a-form-item>
        </a-col>
        <a-col :sm="{span:12}" :lg="{span:12}">
          <a-form-item label="所属院系">
            <a-select mode="multiple" optionFilterProp="children" style="width: 100%" :tokenSeparators="[',']" @change="handleChange"
              placeholder="请输入..."  v-decorator="[
                    'ssyxm',
                    {
                        rules: [{ required: true, message: '请输入所属院系!' }],
                    }
                    ]">
              <a-select-option v-for="i in selectMenu.yx" :key='i.id' :value='i.dwh'>{{i.dwmc}}</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>

      </a-row>
      <a-table ref="table" size="default" rowKey="key" bordered :columns="columns" :dataSource="data" :pagination="false"
        :scroll="{ x: 1500 }">
        <template v-for="col in ['smmc', 'smzz','cbrq', 'smcbs']" :slot="col" slot-scope="text, record">
          <div :key="col">
            <a-date-picker v-if="col =='cbrq'" :format="dateFormat" @change="(date, dateString) => handlePressChange(record.key,'cbrq',date, dateString)" />
            <a-input style="margin: -5px 0" v-else :value="text" @change="e => handleChange(e.target.value, record.key, col)" />
          </div>
        </template>
        <template slot="action" slot-scope="text,record">
          <a @click="handleDelete(record.key)">删除</a>
        </template>
      </a-table>
    </a-form>
    <div style="padding:10px 0;">
      <a-button style="margin-right: .8rem" type="primary" block @click="handleAddLine">新增行</a-button>
    </div>
    <div class="drawer-bootom-button">
      <a-button style="margin-right: .8rem" @click="onClose">取消</a-button>
      <a-button @click="handleSubmit" type="primary" :loading="loading">保存</a-button>
    </div>
  </a-drawer>
</template>

<script>
  // import moment from 'moment'
  import {
    STable
  } from '~'
  import {
    mapState
  } from 'vuex'

  const formItemLayout = {
    labelCol: {
      span: 3
    },
    wrapperCol: {
      span: 18
    }
  }

  const selectArr = ['TYPE0390', 'TYPE0075', 'TYPE0125', 'TYPE0072']
  export default {
    name: 'ReferenceManageAdd',
    props: {
      referenceManageAddVisiable: {
        default: false
      }
    },
    components: {
      STable
    },
    data() {
      return {
        dateFormat: 'YYYY-MM-DD HH:mm:ss',
        formItemLayout,
        loading: false,
        windowWidth:"650",
        winWidth:"650",
        data: [],
        postParams: {
          hzfs: 'yx'
        },
        // 表头
        columns: [{
            title: '书目名称',
            dataIndex: 'smmc',
            scopedSlots: {
              customRender: 'smmc'
            }
          },
          {
            title: '书目作者',
            dataIndex: 'smzz',
            scopedSlots: {
              customRender: 'smzz'
            }
          },
          {
            title: '书目出版社',
            dataIndex: 'smcbs',
            scopedSlots: {
              customRender: 'smcbs'
            }
          },
          {
            title: '出版日期',
            dataIndex: 'cbrq',
            scopedSlots: {
              customRender: 'cbrq'
            }
          },
          {
            title: '操作',
            dataIndex: 'cz',
            fixed: 'right',
            width: 120,
            scopedSlots: {
              customRender: 'action'
            }
          }
        ],
        selectMenu: {
          yx: [] // 院系
        }
      }
    },
    beforeCreate() {
      this.form = this.$form.createForm(this)
    },
    computed: {
      ...mapState({
        systemInfo: state => state.app.systemInfo,
        TYPE0390: state => state.app['TYPE0390'] // 年级
      })
    },
    created() {
      this.initSelectMenu()
      selectArr.forEach(v => {
        this.$store.dispatch('app/setDictionary', v)
      })
    },
    watch:{
      winWidth(val){
        let that = this
        setTimeout(function(){
          if(val<650){
            that.windowWidth=val
          }else{
            that.windowWidth="650"
          }
        },400)
      }
    },
    mounted(){
        //监听屏幕宽度,放入winWidth
    const that=this
     that.windowWidth = document.body.clientWidth>450?450:document.body.clientWidth
    window.onresize=()=>{
      return (()=>{
        window.screenWidth=document.body.clientWidth
        that.winWidth=window.screenWidth
      })()
    }
    },
    methods: {
      initSelectMenu() {
        let allRequest = [
          this.$api.base.collegeAll()
        ]
        Promise.all(allRequest).then(res => {
          this.selectMenu = {
            yx: res[0].data
          }
        })
      },
      reset() {
        this.data = []
      },
      // 选择院系
      yxChange(code) {
        this.$set(this.queryParam, 'sszym', '')
        this.$set(this.selectMenu, 'zy', '')
        if (code) {
          this.$api.base.majorAll({
            lsdwh: code
          }).then(res => {
            this.$set(this.selectMenu, 'zy', res.data)
          })
        }
      },
      handleChange(value, key, column) {
        const newData = [...this.data]
        const target = newData.filter(item => key === item.key)[0]
        if (target) {
          target[column] = value
          this.data = newData
        }
      },
      // 新增行
      handleAddLine() {
        this.data.push({
          smmc: '',
          smzz: '',
          smcbs: '',
          cbrq: '',
          key: Math.random().toString(26).substring(2)
        })
      },
      // 选择招生年度
      zsndChange() {

      },
      // 关闭
      onClose() {
        this.reset()
        this.data = []
        this.postParams = {}
        this.form.resetFields()
        //  this.$set(this.postParams,'kmbm','')
        //  this.$set(this.postParams,'kmlxm','')
        //  this.$set(this.postParams,'kmmc','')
        //  this.$set(this.postParams,'ssyxm','')
        this.$emit('close')
      },
      // 设置时间
      handlePressChange(key, dataIndex, date, dateString) {
        const dataSource = [...this.data]
        const target = dataSource.find(item => item.key === key)
        if (target) {
          target[dataIndex] = dateString
          this.data = dataSource
        }
      },
      // 保存
      handleSubmit() {
        var newObj = this.form.getFieldsValue()
        newObj.ssyxm = newObj.ssyxm.join(',')
        var params = Object.assign(newObj, {
          "details": this.data
        })
        // this.reset()
        // this.$emit('success')
        this.form.validateFields((err, values) => {
          if (err) {
            this.$message.error("请选择必填项")
          } else {
            this.$api.doctorRecruit
              .consultAdd(params)
              .then(res => {
                this.$emit("success");
                   this.data = []
                this.postParams = {}
                this.form.resetFields()
              })
              .finally(() => {
                this.loadingBtn = false;
                //  this.form.resetFields()
                this.postParams = ''
                this.data = []
              });
          }
        })

      },
      handleDelete(key) {
        const dataSource = [...this.data]
        this.data = dataSource.filter(item => item.key !== key)
      }
    }
  }
</script>
